﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.IO;
using System.Linq;
using System.Runtime;
using System.Text;
using System.Threading.Tasks;
using BigMonitoringWarningApi.Model.ApiResult;
using GYCTOAManagementSystemNewApi.Controllers.PublicController;
using GYCTOAManagementSystemNewApi.Controllers;
using GYCTOAManagementSystemNewApi.Model;
using GYCTOAManagementSystemNewApi.Model.API;
using GYCTOAManagementSystemNewApi.Model.Enum;
using GYCTOAManagementSystemNewApi.Model.Tool;
using GYCTOAManagementSystemNewApi.Public;
using GYCTOAManagementSystemNewApi.Tool;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.VisualBasic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using SharpCompress.Common;
using GYCTOAManagementSystemNewApi.Model.Response;
using OfficeOpenXml;
using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder;
using GYCTOAManagementSystemNewApi.Model.Entity;
using BigMonitoringWarningApi.Tool.Extension;
using GYCTOAManagementSystemNewApi.Model.Enum.PayrollForm;

namespace GYCTOAManagementSystemNewApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    //[Authorize]
    public class UserInfoController : Controller
    {
        DBContext db;
        Message mes;
        GlobalPublic globalPublic;

        public UserInfoController(DBContext _db, Message _mes, GlobalPublic _globalPublic)
        {
            db = _db;
            mes = _mes;
            globalPublic = _globalPublic;
        }

        #region 人员管理
        ///// <summary>
        ///// 用户文件上传文件
        ///// </summary>
        ///// <param name="filedata"></param>
        ///// <returns></returns>
        //[HttpPost]
        //public ActionResult Savefile()
        //{
        //    try
        //    {
        //        var files = System.Web.HttpContext.Current.Request.Files["files"];
        //        var type = System.Web.HttpContext.Current.Request["type"];
        //        var path = Server.MapPath("/") + "Userinfo";
        //        var PersonalResume = Server.MapPath("/") + "Userinfo/peopleResume";
        //        var SkillsCertificate = Server.MapPath("/") + "Userinfo/SkillsCertificate";
        //        if (!Directory.Exists(path))
        //        {
        //            Directory.CreateDirectory(path);
        //        }
        //        if (!Directory.Exists(PersonalResume))
        //        {
        //            Directory.CreateDirectory(PersonalResume);
        //        }
        //        if (!Directory.Exists(SkillsCertificate))
        //        {
        //            Directory.CreateDirectory(SkillsCertificate);
        //        }
        //        string newpath = "";
        //        switch (type.ToString())
        //        {
        //            case "PersonalResume":
        //                newpath = PersonalResume + "/" + files.FileName;
        //                break;
        //            default:
        //                newpath = SkillsCertificate + "/" + files.FileName;
        //                break;
        //        }
        //        files.SaveAs(newpath);
        //        return new JsonResult(true);
        //    }
        //    catch (Exception)
        //    {
        //        return new JsonResult(false);
        //    }
        //}
        ///// <summary>
        /// 根据标识获取用户信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        private Users GetUsers(int Id)
        {
            return db.Users.Where(l => l.Id == Id).FirstOrDefault();
        }
        /// <summary>
        /// 文件删除
        /// </summary>
        /// <param name="path">路径</param>
        /// <returns></returns>
        private bool DelFile(string path)
        {
            // var newpath = Server.MapPath("/Userinfo/" + path);
            var pathurl = AppDomain.CurrentDomain.BaseDirectory;
            var root = Path.GetPathRoot(path);
            var newpath = Path.Combine(pathurl, "Userinfo", path);
            //string serverPath = root + "CompanyFile\\" + "1\\" + FileType;//1代表OA系统
            if (System.IO.File.Exists(newpath))  //判断路径是否存在 
            {
                FileInfo file = new FileInfo(newpath);
                if (file.Exists)
                {
                    file.Delete();
                    return true;
                }
                return false;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region 人员管理

        [HttpPost("GetInternshipState")]
        public JsonResult GetInternshipState()
        {
            var lis = PublicTool.GetEnumDESVal<InternshipStateEnum>();
            return new JsonResult(new { lis = lis });
        }
        //public ActionResult AddEmploy()
        //{
        //    return View();
        //}

        [HttpPost("UpdateEmploy")]
        public JsonResult UpdateEmploybit(int id = -1)
        {
            var obj = db.Users.Where(l => l.Id == id).FirstOrDefault();
            mes.IsSuccess = false;
            if (obj == null)
            {
                mes.Msg = "暂无该条数据";
                return new JsonResult(new { mes = mes });
            }
            mes.IsSuccess = true;
            return new JsonResult(new { mes = mes, obj = obj });
        }
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="limit"></param>
        /// <param name="offset"></param>
        /// <returns></returns>
        [HttpPost("GetUsersContent")]
        public JsonResult GetUsersContent(int limit, int offset)
        {
            var list = db.Users.Where(x => x.JobNumber != "admin" && (int)x.InternshipState != 8).ToList();
            var total = list.Count;
            var rows = list/*.OrderBy(x => x.DepartmentId).Take(limit * offset).Skip(limit * (offset - 1))*/.ToList();
            //var ret = JsonConvert.SerializeObject(rows, setting);
            return new JsonResult(new { code = 0, msg = "", count = total, data = rows });
        }
        /// <summary>
        /// 增加用户
        /// </summary>
        /// <param name="users"></param>
        /// <returns></returns>
        [HttpPost("AddUsersContent")]
        public JsonResult AddUsersContent([FromBody] dynamic formData)
        {
            //AttendanceSet attendanceSet)
            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            var users = JsonConvert.DeserializeObject<Users>(jsondata["users"].ToString());

            var firuser = db.Users.Where(x => x.Phone.Equals(users.Phone)).FirstOrDefault();
            if (firuser == null)
            {
                var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
                var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
                //Users users
                users.Pinyin = String.Join(",", PinYinConverterHelp.GetTotalPinyin(users.UserName).AllPingYin);
                //users.PersonalResume = PersonalResume;
                //users.SkillsCertificate = SkillsCertificate;
                PublicTool.GetOpDataOpId(users, author);
                db.Users.Add(users);
                db.SaveChanges();
                //users.UserNumber = DateAndTime.Now.ToString("yyyyMMdd") + users.Id;
                db.Users.Update(users);
                return new JsonResult(new { flag = db.SaveChanges() > 0, id = users.Id });
            }
            return new JsonResult(new { flag = false, id = users.Id, bit = false });
        }

        /// <summary>
        /// 下载身份证
        /// </summary>
        /// <returns></returns>
        [HttpGet("DwonUserFile")]
        public IActionResult DwonUserFile(string downPath)
        {
            var pdfBytes = System.IO.File.ReadAllBytes(downPath);
            // 生成PDF文件
            MemoryStream stream = new MemoryStream(pdfBytes);
            stream.Position = 0;
            var fileName = Path.GetFileName(downPath);
            return File(stream, "application/pdf", fileName);
        }


        /// <summary>
        /// 下载银行卡
        /// </summary>
        /// <returns></returns>
        [HttpPost("DwonBankCard")]
        public JsonResult DwonBankCard([FromBody] dynamic formData)
        {
            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            var users = JsonConvert.DeserializeObject<Users>(jsondata["user"].ToString());
            var type = Convert.ToInt32((jsondata["type"].ToString()));
            //人员备份只保留最新的数据
            var serverPath = PublicTool.GetPaht(1, users.Id, type, false);
            var file = new DirectoryInfo(serverPath);
            if (!Directory.Exists(serverPath))  //判断路径是否存在 
            {
                return new JsonResult(new { success = false, path = "" });
            }
            if (file.GetFiles().Count() == 0)
            {
                return new JsonResult(new { success = false, path = "" });
            }
            var path = PublicTool.DownDPFByImg(users.UserName + "银行卡", file.GetFiles().LastOrDefault().FullName);
            //path = PublicTool.DownFileReplace(path);
            return new JsonResult(new { success = true, path = path, filename = Path.GetFileName(path) });
        }


        /// <summary>
        /// 下载身份证
        /// </summary>
        /// <returns></returns>
        [HttpPost("DwonUserID")]
        public JsonResult DwonUserID([FromBody] dynamic formData)
        {
            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            var users = JsonConvert.DeserializeObject<Users>(jsondata["user"].ToString());
            //人员备份只保留最新的数据
            var serverPath = PublicTool.GetPaht(1, users.Id, 1, false);
            var file = new DirectoryInfo(serverPath);
            if (!Directory.Exists(serverPath))  //判断路径是否存在 
            {
                return new JsonResult(new { success = false, path = "" });
            }
            if (file.GetFiles().Count() == 0)
            {
                return new JsonResult(new { success = false, path = "" });
            }
            //var path = PublicTool.DownDPFByImg(users.UserName + "身份证", file.GetFiles().LastOrDefault().FullName);
            //原来为只能上传1张图片，并且pdf中只保留一张图片，20250818修改为可保留多张图片
            string path = "";
            foreach (var f in file.GetFiles())
            {
                path = PublicTool.DownDPFByImg(users.UserName + "身份证", f.FullName);
            }
            //path = PublicTool.DownFileReplace(path);
            return new JsonResult(new { success = true, path = path, filename = Path.GetFileName(path) });
        }


        /// <summary>
        /// 导出Excel
        /// </summary>
        [HttpPost("GetUserInfoExcel")]
        public JsonResult GetUserInfoExcel(int[] arrDel)
        {
            List<string[]> strings = new();
            //找到对应的用户对象
            var userlist = db.Users.Where(x => arrDel.Contains(x.Id)).ToList();
            foreach (var item in userlist)
            {
                strings.Add(new string[] { item.UserName + "\t", item.UserNumber + "\t", item.Card + "\t", item.Phone + "\t", item.BankName + "\t", item.BankCardNumber + "\t" });
            }
            var csvContent = PublicTool.createexcel(new string[] { "姓名", "工号", "身份证号", "电话号码", "银行", "银行卡号", }, strings);
            string filePath = Path.Combine(PublicMethodApiController.StaticFilePath, Path.GetFileNameWithoutExtension("user") + ".csv");
            System.IO.File.WriteAllText(filePath, csvContent.ToString(), Encoding.UTF8);
            return new JsonResult(new { success = true, path = "OAFile/user.csv" });
        }
        /// <summary>
        /// 删除身份证
        /// </summary>
        /// <param name="users"></param>
        /// <returns></returns>
        [HttpPost("DeleUserID")]
        public ApiResult DeleUserID([FromBody] dynamic formData)
        {
            //AttendanceSet attendanceSet)
            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            var users = Convert.ToInt32(jsondata["Id"].ToString());
            //人员备份只保留最新的数据
            var serverPath = PublicTool.GetPaht(1, users, 1, false);
            PublicTool.DeleteFile(serverPath, true);
            return ApiResult.True(serverPath);
        }
        /// <summary>
        /// 删除银行卡
        /// </summary>
        /// <param name="users"></param>
        /// <returns></returns>
        [HttpPost("DeleBankCard")]
        public ApiResult DeleBankCard([FromBody] dynamic formData)
        {
            try
            {
                //AttendanceSet attendanceSet)
                var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
                var users = Convert.ToInt32(jsondata["Id"].ToString());
                var type = Convert.ToInt32(jsondata["type"].ToString());

                //人员备份只保留最新的数据
                var serverPath = PublicTool.GetPaht(1, users, type, false);
                PublicTool.DeleteFile(serverPath, true);
                return ApiResult.True();
            }
            catch (Exception ex)
            {
                return ApiResult.False(ex.Message);
            }
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="OldPassword"></param>
        /// <param name="NewPassword"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("EditPassword")]
        public JsonResult EditPassword([FromBody] dynamic formData)
        {
            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            string OldPassword = jsondata["OldPassword"].ToString();
            string NewPassword = jsondata["NewPassword"].ToString();
            int id = Convert.ToInt32(jsondata["id"].ToString());
            Message mes = new Message();
            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];

            TokenManage token = new TokenManage();
            /*string passwordMD5 = MD5Encrypt.Encrypt(NewPassword);
            string OldPasswordMD5 = MD5Encrypt.Encrypt(OldPassword);
*/
            Users u = db.Users.Find(id);


            if (NewPassword == OldPassword)
            {
                mes.IsSuccess = false;
                mes.Msg = "新密码不能与旧密码相同";
                return new JsonResult(new { mes = mes });
            }
            else if (u.Password != OldPassword)
            {
                mes.IsSuccess = false;
                mes.Msg = "旧密码错误，且不能与旧密码请联系管理员";
                return new JsonResult(new { mes = mes });
            }
            else
            {
                u.Password = NewPassword;
                PublicTool.GetOpDataOpId(u, author);
                mes.IsSuccess = db.SaveChanges() > 0 ? true : false;
                mes.Msg = mes.IsSuccess ? "密码修改成功" : "密码修改失败";
                return new JsonResult(new { mes = mes });
            }
        }
        /// <summary>
        /// 获取用户列表信息
        /// </summary>
        /// <param name="formData"></param>
        /// <returns></returns>
        [HttpPost("GetUsersDetail")]
        public JsonResult GetUsersDetail([FromBody] dynamic formData)
        {
            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            var users = JsonConvert.DeserializeObject<Users>(jsondata["users"].ToString());
            var offset = Convert.ToInt32(jsondata["offset"].ToString());
            var limit = Convert.ToInt32(jsondata["limit"].ToString());
            //int limit, int offset, Users users)
            var a = users;
            var sql = "";
            var ac = users.InternshipState;
            if (users.InternshipState == null || users.InternshipState == 0)
            {
                sql = "select * from Users where 1=1 and  UserName!= '超级管理员' and  InternshipState !=" + (int)InternshipStateEnum.Quit + " ";
            }
            else
            {
                sql = "select * from Users where 1=1 and    UserName!= '超级管理员' and InternshipState =" + (int)users.InternshipState + " ";
            }
            //if (users.DepartmentId > 0)
            //{
            //    sql += "and DepartmentId='" + users.DepartmentId + "' ";
            //}
            if (users.UserName != null)
            {
                sql += "and UserName like '%" + users.UserName + "%' ";
            }
            if (users.Card != null)
            {
                sql += "and Card like '%" + users.Card + "%' ";
            }
            if (users.Phone != null)
            {
                sql += "and Phone like '%" + users.Phone + "%' ";
            }
            if (users.JobNumber != null)
            {
                sql += "and JobNumber like '%" + users.JobNumber + "%' ";
            }
            //var query = db.Users.FromSqlRaw(sql).Where(x => !x.Delete).ToList();
            var query = db.Users.FromSqlRaw(sql).ToList();
            if (!users.Delete)
                query = query.Where(x => !x.Delete).ToList();
            else
                query = query.Where(x => x.Delete).ToList();
            var list = query/*.OrderBy(x => x.DepartmentId).OrderBy(y => Convert.ToInt32(db.DutyMains.Where(x => x.Id.ToString() == y.UserPosition).FirstOrDefault().Level))*/.Skip(limit * (offset - 1)).Take(limit).ToList();
            //var ret = JsonConvert.SerializeObject(rows, setting);
            return new JsonResult(new { code = 0, msg = "", count = query.Count, data = list });
        }
        /// <summary>
        /// 判断是否有重复的点击转正
        /// </summary>
        /// <param name="users"></param>
        /// <returns></returns>
        /// 
        [HttpPost("UpInternshipState")]
        public JsonResult UpInternshipState([FromBody] dynamic formData)
        {

            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            var users = JsonConvert.DeserializeObject<Users>(jsondata["users"].ToString());
            var number = db.Users.Where(x => x.Id == users.Id).FirstOrDefault().InternshipState;//在职员工不能再一次转正
            var bol = (number == users.InternshipState) == true ? 0 : 1;
            return new JsonResult(new { bol = bol });
        }
        /// <summary>
        /// 删除用户信息
        /// </summary>
        /// <param name="arrDel"></param>
        /// <returns></returns>
        [HttpPost("DeleteUsersContent")]
        public ApiResult DeleteUsersContent([FromBody] UserIdArr reqset)
        {
            foreach (var tid in reqset.ids)
            {
                var obj = GetUsers(tid);
                if (obj == null)
                {
                    return ApiResult.False("当前查无此人");
                }
                obj.Delete = true;
                db.Update(obj);
                PublicTool.GetPaht(1, tid, 1, true);
                PublicTool.GetPaht(1, tid, 2, true);
            }
            db.SaveChanges();
            return ApiResult.True();
        }
        /// <summary>
        /// 恢复已删除用户信息
        /// </summary>
        /// <param name="arrDel"></param>
        /// <returns></returns>
        [HttpPost("RecoverDeleteUsersContent")]
        public ApiResult RecoverDeleteUsersContent([FromBody] dynamic formData)
        {
            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            var users = JsonConvert.DeserializeObject<Users>(jsondata.ToString());
            Users u = db.Users.Find(users.Id);
            u.Delete = false;
            db.SaveChanges();
            return ApiResult.True();
        }
        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="formData"></param>
        /// <returns></returns>
        [HttpPost("UpdateUsersContent")]
        public JsonResult UpdateUsersContent([FromBody] dynamic formData)
        {

            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            var users = JsonConvert.DeserializeObject<Users>(jsondata["users"].ToString());
            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
            var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);

            //users.PersonalResume = PersonalResume;
            //users.SkillsCertificate = SkillsCertificate;
            //users.OperatorId = Public.GetUserId();//修改人员操作人
            //users.OperatDate = DateTime.Now;//修改人员操作人

            PublicTool.GetOpDataOpId(users, author);

            users.Pinyin = String.Join(",", PinYinConverterHelp.GetTotalPinyin(users.UserName).AllPingYin);
            var entry = db.Entry<Users>(users);
            entry.State = EntityState.Unchanged;
            entry.Property(t => t.UserName).IsModified = true; //设置要更新的属性
            //entry.Property(t => t.Birth).IsModified = true; //设置要更新的属性
            entry.Property(t => t.Card).IsModified = true; //设置要更新的属性
            //entry.Property(t => t.Password).IsModified = true; //设置要更新的属性
            entry.Property(t => t.JobNumber).IsModified = true; //设置要更新的属性
            //员工工号
            entry.Property(t => t.UserNumber).IsModified = true; //设置要更新的属性
            //entry.Property(t => t.DepartmentId).IsModified = true; //设置要更新的属性
            //entry.Property(t => t.Email).IsModified = true; //设置要更新的属性
            entry.Property(t => t.FamilyAddress).IsModified = true; //设置要更新的属性
            //entry.Property(t => t.InductionTime).IsModified = true; //设置要更新的属性
            entry.Property(t => t.InternshipState).IsModified = true; //设置要更新的属性
            entry.Property(t => t.Phone).IsModified = true; //设置要更新的属性
            entry.Property(t => t.Pinyin).IsModified = true; //设置要更新的属性
            entry.Property(t => t.Remark).IsModified = true; //设置要更新的属性
            entry.Property(t => t.Sex).IsModified = true; //设置要更新的属性
            //entry.Property(t => t.UserPosition).IsModified = true; //设置要更新的属性
            entry.Property(t => t.RoleId).IsModified = true; //设置要更新的属性
            //entry.Property(t => t.SalaryStandard).IsModified = true; //设置要更新的属性
            entry.Property(t => t.BankCardNumber).IsModified = true; //设置要更新的属性
            entry.Property(t => t.BankName).IsModified = true; //设置要更新的属性

            entry.Property(t => t.BankCardNumber2).IsModified = true; //设置要更新的属性
            entry.Property(t => t.BankName2).IsModified = true; //设置要更新的属性
            //2019年8月21日18:38:30添加属性,合同开始时间,结束时间
            //entry.Property(t => t.LabourDeadlineEnd).IsModified = true; //设置要更新的属性
            //entry.Property(t => t.LabourDeadlineStart).IsModified = true; //设置要更新的属性
            //entry.Property(t => t.RegularDate).IsModified = true; //设置要更新的属性
            //2020年4月1日17:32:41添加属性 现居地
            entry.Property(t => t.NowFamilyAddress).IsModified = true; //设置要更新的属性
            //2020年4月24日14:52:41添加属性 学历+毕业学校
            //entry.Property(t => t.Education).IsModified = true;//设置要更新的属性
            //entry.Property(t => t.GraduateSchool).IsModified = true;//设置要更新的属性
            //2020年4月27日14:36:59添加属性修改时间  职位职责
            entry.Property(t => t.OperatDate).IsModified = true;//设置要更新的属性
            entry.Property(t => t.OperatId).IsModified = true;//设置要更新的属性
                                                              //entry.Property(t => t.RoleDuty).IsModified = true;//设置要更新的属性
                                                              //2020年12月28日14:36:59添加属性岗位 岗位等级、个人简介
                                                              //entry.Property(t => t.Post).IsModified = true;//设置要更新的属性
                                                              //entry.Property(t => t.PostLevel).IsModified = true;//设置要更新的属性
                                                              //entry.Property(t => t.PersonalProfile).IsModified = true;//设置要更新的属性
                                                              // entry.Property(t => t.OpenBalance).IsModified = true; //设置要更新的属性

            var flag = db.SaveChanges() > 0;
            return new JsonResult(new { flag = flag });
        }

        /// <summary>
        /// 更改员工状态
        /// </summary>
        /// <param name="users"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("UpdataInternshipState")]
        public JsonResult UpdataInternshipState([FromBody] dynamic formData)
        {

            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            var users = JsonConvert.DeserializeObject<Users>(jsondata["users"].ToString());
            int id = Convert.ToInt32(jsondata["id"].ToString());

            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
            var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);

            var newusers = db.Users.Where(x => x.Id == users.Id).FirstOrDefault();
            PublicTool.GetOpDataOpId(newusers, author);
            switch (id)
            {
                case 1://转正
                    newusers.InternshipState = 1;
                    newusers.InductionTime = DateTime.Now;
                    newusers.DepartureTime = null;
                    //newusers.RegularDate = null;
                    break;

                case 4://转正
                    newusers.InternshipState = 4;
                    //newusers.RegularDate = DateTime.Now;
                    newusers.DepartureTime = null;
                    break;

                case 8:
                    newusers.InternshipState = 8;
                    newusers.DepartureTime = DateTime.Now;
                    break;
                default:
                    break;
            }
            var flag = db.SaveChanges() > 0 ? true : false;
            return new JsonResult(new { flag = flag });
        }

        /// <summary>
        /// 推送员工人员
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetEmployeeUsers")]
        public ApiResult GetEmployeeUsers()
        {
            string EmployeeRoleId = ConfigurationHelper.GetConfigHeadRoleId("UserId");
            var Employees = db.Users.Where(x => x.RoleId == (EmployeeRoleId) && !x.Delete).ToList();//在职员工不能再一次转正
            return ApiResult.True(Employees);
        }
        #endregion

        #region 薪资构成
        /// <summary>
        /// 薪资构成主页面
        /// </summary>
        /// <returns></returns>
        //public ActionResult SalaryStructure()
        //{
        //    return View();
        //}
        ///// <summary>
        ///// 添加页面
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //public ActionResult AddSalaryStructure()
        //{
        //    return View();
        //}
        #endregion

        #region 主页面数据
        /// <summary>
        /// 主页面获取数据
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetUsserInfoDetails")]
        public JsonResult GetUsserInfoDetails([FromBody] dynamic formData)
        {
            JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
            int userid = Convert.ToInt32(j_token["userid"]);
            var userinfo = db.Users.Where(x => x.Id.Equals(userid)).FirstOrDefault();
            return Json(userinfo);
        }
        #endregion

        #region App端需求接口
        private static readonly object formlock = new object();

        /// <summary>
        /// 获取对应账户详情
        /// </summary>
        /// <param name="formData"></param>
        /// <returns></returns>
        [HttpGet("GetUserInfoDefault")]
        public JsonResult GetUserInfoDefault(int id)
        {
            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
            var logid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
            var right = TokenManage.GetTokenValues(author)[2].Value;
            Model.Users user = new Users();
            string headurl = "";

            Message aresult = new Message();
            aresult.IsSuccess = false;
            aresult.Code = (int)ApiStatusCodeEnum.Code200;
            aresult.Msg = "操作失败,请重试!";

            if (!right.Contains("010300"))
            {
                aresult.Msg = "你没有权限操作!";
                return new JsonResult(new { reuslt = aresult, user = user, headurl = headurl });
            }
            else
            {
                user = db.Users.Where(x => x.Id.Equals(id)).FirstOrDefault();
                string headportrait = Path.GetPathRoot(AppDomain.CurrentDomain.BaseDirectory) + PublicMethodApiController.FileloadStr + "/1/" + (int)FileTypeEnum.UserFile + "/" + user.Id + "/3";
                var filename = IsExistenceFile(headportrait);
                if (!IsExistenceFile(headportrait).Equals(""))
                {
                    headurl = "/OAFile/" + (int)FileTypeEnum.UserFile + "/" + user.Id + "/3/" + filename;
                }
                aresult.Msg = "操作成功!";
                aresult.IsSuccess = true;
            }
            return new JsonResult(new { reuslt = aresult, user = user, headurl = headurl });
        }
        /// <summary>
        /// 判断头像是否存在,存在返回文件名称
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private string IsExistenceFile(string url)
        {
            var filename = "";
            bool result = System.IO.Directory.Exists(url);
            if (result)
            {
                filename = Directory.GetFiles(url).FirstOrDefault();
                FileInfo info = new FileInfo(filename);
                filename = info.Name;
            }
            return filename;
        }
        #endregion



        #region 人员身份证批量下载下载


        /// <summary>
        /// 批量下载身份证
        /// </summary>
        /// <returns></returns>
        [HttpPost("DwonUserIDArr")]
        public ApiResult DwonUserIDArr([FromBody] UserIdArr request)
        {
            //批量下载文件地址
            var copyserverPath = PublicTool.GetPaht(1, 1, 3, true);

            List<string> UserNamelist = new List<string>();
            foreach (var item in request.ids)
            {
                var user = db.Users.FirstOrDefault(x => x.Id == item);
                //人员备份只保留最新的数据
                var serverPath = PublicTool.GetPaht(1, user.Id, 1, false);
                var file = new DirectoryInfo(serverPath);
                if (!Directory.Exists(serverPath))  //判断路径是否存在 
                {
                    return ApiResult.False();
                }
                if (file.GetFiles().Length == 0)
                {
                    UserNamelist.Add(user.UserName);
                }
                else
                {
                    var path = PublicTool.DownDPFByImg(user.UserName + "身份证", file.GetFiles().FirstOrDefault().FullName);
                    System.IO.File.Copy(path, Path.Combine(copyserverPath, new FileInfo(path).Name), true);
                }
            };
            if (UserNamelist.Any())
            {
                return ApiResult.False(string.Join(",", UserNamelist) + "未上传身份证数据");
            }
            else {
                return ApiResult.True(new DownFileProp()
                {
                    FileName = "",
                    FileType = 1,
                    id = 1,
                    Type = 3,
                });
            }

        }
        #endregion

        #region 人员银行卡批量下载


        /// <summary>
        /// 批量下载银行卡
        /// </summary>
        /// <returns></returns>
        [HttpPost("DwonBankCardArr")]
        public ApiResult DwonBankCardArr([FromBody] UserIdArr request)
        {
            //批量下载文件地址
            var copyserverPath = PublicTool.GetPaht(1, 1, 4, true);
            List<string> UserNamelist = new List<string>();
            foreach (var item in request.ids)
            {
                var user = db.Users.FirstOrDefault(x => x.Id == item);
                //人员备份只保留最新的数据
                var serverPath = PublicTool.GetPaht(1, user.Id, 2, false);
                var file = new DirectoryInfo(serverPath);
                if (!Directory.Exists(serverPath))  //判断路径是否存在 
                {
                    return ApiResult.False();
                }
                if (file.GetFiles().Length == 0)
                {
                    UserNamelist.Add(user.UserName);
                }
                else
                {
                    var path = PublicTool.DownDPFByImg(user.UserName + "银行卡", file.GetFiles().FirstOrDefault().FullName);
                    System.IO.File.Copy(path, Path.Combine(copyserverPath, new FileInfo(path).Name), true);
                }
            };
            if (UserNamelist.Any())
            {
                return ApiResult.False(string.Join(",", UserNamelist) + "未上传银行卡数据");
            }
            else
            {
                return ApiResult.True(new DownFileProp()
                {
                    FileName = "",
                    FileType = 1,
                    id = 1,
                    Type = 4,
                });
            }
        }
        #endregion

        //[HttpPost("HDRYdan")]
        //public void HDRYdan()
        //{
        //    string filePath = "D:\\CompanyProject\\生活费.xlsx";
        //    if (System.IO.File.Exists(filePath))
        //    {

        //        List<Users> users = new List<Users>();
        //        FileInfo existingFile = new FileInfo(filePath);
        //        ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
        //        using (ExcelPackage package = new ExcelPackage(existingFile))
        //        {
        //            ExcelWorksheet worksheet = package.Workbook.Worksheets[0]; // 读取第一个工作表

        //            int rowCount = 55;
        //            int colCount = worksheet.Dimension.Columns;
        //            var datesplit = "2024-02-29,2024-03-10,2024-03-21,2024-04-01,2024-04-10,2024-04-20,2024-05-01,2024-05-10,2024-05-20,2024-05-30,2024-06-04,2024-06-27,2024-07-01,2024-07-10,2024-07-20,2024-08-01".Split(',');
        //            int index = 0;

        //            for (int col = 3; col <= colCount; col++)
        //            {
        //                if (col == 4 || col == 7 || col == 11 || col == 16 || col == 19 || col == 23 || col == 27 || col == 2)
        //                {
        //                    if (col == 27)
        //                    {

        //                    }
        //                    continue;
        //                }
        //                List<LivingexpensesInfo> t1 = new List<LivingexpensesInfo>();
        //                for (int row = 4; row <= rowCount; row++)
        //                {
        //                    {
        //                        var dataname = worksheet.Cells[row, 1].Value.ToString().Trim();
        //                       var moneystr= worksheet.Cells[row, col].Value;
        //                        decimal money = 0;
        //                        if (moneystr!=null)
        //                        {
        //                            money = moneystr.ToDecimal();
        //                        }
        //                        var livingName= datesplit[index].ToString();
        //                            var  Livingexpensesdata= db.Livingexpenses.Where(x => x.LivingeBatch == livingName).ToList();
                              
        //                        int id = Livingexpensesdata.FirstOrDefault().Id;
        //                        var data = new LivingexpensesInfo();
        //                        data.Socialinsurance = 0;
        //                        data.UserId= db.Users.FirstOrDefault(x => x.UserName == dataname).Id;
        //                        data.LivingexpensesId  = id;
        //                        data.Delete = false;
        //                        data.OperatId = 104;
        //                        data.OperatDate = DateTime.Now;
        //                        data.Money = money;
        //                        data.SettlementNumber = "";  
        //                        data.Settlement = false;  
        //                        data.OrderStatus = RealOrderStateEnum.Success;  
        //                        data.Socialinsurance = 0;
        //                        t1.Add(data);
        //                    }
        //                }
        //                db.LivingexpensesInfo.AddRange(t1);
        //                db.SaveChanges();
        //                index++;
        //            }
        //        }
        //    }
        //    else
        //    {
        //        Console.WriteLine("Excel file not found.");
        //    }
        //}
   
    
    
    }
}